//
//  NNAddTextView.swift
//  CommonTool
//
//  Created by Name i on 2022/3/22.
//

import Foundation
import UIKit



public class NNAddInfoModel: NSObject {
    var placeHolder: String = "请输入文本"
    var contentText: String = ""
    var defaultFont: UIFont = UIFont.boldSystemFont(ofSize: 18)
    var defaultColor: UIColor = UIColor.purple
}


protocol NNAddTextViewDelegate: NSObjectProtocol {
    func shouldBeginEditing(addtextView: NNAddTextView)
}



class NNAddTextView: UIView {
    
    
    private lazy var contentView: UILabel = {
        let contentView = UILabel()
        contentView.numberOfLines = 0
        contentView.textColor = UIColor.orange
        return contentView
    }()
    
    private lazy var rotateCtrl: UIImageView = {
        let img = UIImageView(frame: CGRect(x: frame.size.width - kControlWH,
                                            y: frame.size.height - kControlWH,
                                            width: kControlWH,
                                            height: kControlWH))
        img.image = UIImage(named: "AddView_rotate")
        img.backgroundColor = .random
        img.isUserInteractionEnabled = true
        img.addGestureRecognizer(UIPanGestureRecognizer(target: self,
                                                        action: #selector(rotateControlAction(sender:))))
        return img
    }()
    private lazy var removeCtrl: UIImageView = {
        let img = UIImageView(frame: CGRect(x: 0,
                                            y: 0,
                                            width: kControlWH,
                                            height: kControlWH))
        img.image = UIImage(named: "AddView_close")
        img.backgroundColor = .random
        img.isUserInteractionEnabled = true
        img.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                        action: #selector(removeAction(sender:))))
        return img
    }()
    
    private lazy var editCtrl: UIImageView = {
        let img = UIImageView(frame: CGRect(x: 0,
                                            y: 0,
                                            width: kControlWH,
                                            height: kControlWH))
        img.image = UIImage(named: "AddView_close")
        img.backgroundColor = .random
        img.isUserInteractionEnabled = true
        img.addGestureRecognizer(UITapGestureRecognizer(target: self,
                                                        action: #selector(editAction(sender:))))
        return img
    }()

    
    fileprivate lazy var panGesture: UIPanGestureRecognizer = {
        let pan = UIPanGestureRecognizer(target: self, action: #selector(panAction(sender:)))
        pan.delegate = self
        return pan
    }()
    
    fileprivate lazy var tapGesture: UITapGestureRecognizer = {
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(sender:)))
        return tap
    }()


    // 控制按钮的宽度
    fileprivate let controlWH: CGFloat = 20.0
    private var zoomScale: CGFloat = 1.0
    
    fileprivate var lastControlPoint: CGPoint = .zero
    
    public var infoModel: NNAddInfoModel = NNAddInfoModel()
    
    private weak var delegate: NNAddTextViewDelegate?
    
    
    private var isEditing: Bool = false {
        didSet {
            if isEditing {
                removeCtrl.isHidden = false
                editCtrl.isHidden = false
                rotateCtrl.isHidden = false
                addGestureRecognizer(panGesture)
            }else {
                removeCtrl.isHidden = true
                editCtrl.isHidden = true
                rotateCtrl.isHidden = true
                removeGestureRecognizer(panGesture)
            }
        }
    }
    
    
    public func updateEditingStatus(isEditing: Bool) {
        guard let superView = superview else { return }
        superView.subviews.forEach { child in
            if let child = child as? NNAddTextView {
                child.isEditing = false
            }
        }

        self.isEditing = isEditing
    }
    
    
    convenience init(delegate: NNAddTextViewDelegate) {
        self.init(frame: .zero)
        self.delegate = delegate
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubviews(childs: [contentView, removeCtrl, rotateCtrl, editCtrl])
        removeCtrl.snp.makeConstraints { make in
            make.top.left.equalToSuperview()
            make.size.equalTo(CGSize(width: controlWH, height: controlWH))
        }

        rotateCtrl.snp.makeConstraints { make in
            make.bottom.right.equalToSuperview()
            make.size.equalTo(CGSize(width: controlWH, height: controlWH))
        }
        
        editCtrl.snp.makeConstraints { make in
            make.top.right.equalToSuperview()
            make.size.equalTo(CGSize(width: controlWH, height: controlWH))
        }
        
        contentView.snp.makeConstraints { make in
            make.top.equalTo(removeCtrl.snp.bottom)
            make.left.equalTo(removeCtrl.snp.right)
            make.bottom.equalTo(rotateCtrl.snp.top)
            make.right.equalTo(rotateCtrl.snp.left)
        }
        addGestureRecognizer(tapGesture)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func addToSuperView(targetView: UIView, infoModel: NNAddInfoModel) {
        self.infoModel = infoModel
        
        // 计算文本的尺寸
        contentView.font = infoModel.defaultFont
        
        if infoModel.contentText.isEmpty {
            contentView.text = infoModel.placeHolder
        }else {
            contentView.text = infoModel.contentText
        }
                        
        let contentSize  = contentView.sizeThatFits(CGSize(width: maxContentWith(), height: CC.screenH))
        // 计算文本的位置
        self.frame = CGRect(x: targetView.frame.size.width * 0.5 - contentSize.width * 0.5 - controlWH,
                            y: targetView.frame.size.height * 0.5 - contentSize.height * 0.5 - controlWH,
                            width: min(targetView.frame.size.width * 0.5 + controlWH * 2.0, contentSize.width + controlWH * 2.0),
                            height: contentSize.height + controlWH * 2.0)
        
        targetView.subviews.forEach { child in
            if let child = child as? NNAddTextView {
                child.isEditing = false
            }
        }
        self.isEditing = true
        targetView.addSubview(self)
    }

    
    private func updateControlTransfrom() {
        let offset = controlWH * (zoomScale - 1.0) * 0.25
        removeCtrl.transform = removeCtrl.transform.scaledBy(x: 1.0 / zoomScale, y: 1.0 / zoomScale).concatenating(CGAffineTransform(translationX: offset, y: offset))
        editCtrl.transform = editCtrl.transform.scaledBy(x: 1.0 / zoomScale, y: 1.0 / zoomScale).concatenating(CGAffineTransform(translationX: -offset, y: offset))
        rotateCtrl.transform = rotateCtrl.transform.scaledBy(x: 1.0 / zoomScale, y: 1.0 / zoomScale).concatenating(CGAffineTransform(translationX: -offset, y: -offset))
    }
    
    public func textDidChanged(contentText: String?) {
        
        if let text = contentText, !text.isEmpty {
            infoModel.contentText = text
            contentView.text = text
        }else {
            infoModel.contentText = infoModel.placeHolder
            contentView.text = infoModel.placeHolder
        }
                        
        let contentOriginSize = contentView.sizeThatFits(CGSize(width: maxContentWith(), height: CC.screenH))
        let contentTobeSize = CGSize(width: contentOriginSize.width * zoomScale + 10.0,
                                     height: contentOriginSize.height * zoomScale + 10.0)
        bounds = CGRect(origin: .zero,
                        size: CGSize(width: contentTobeSize.width + controlWH * 2.0,
                                     height: contentTobeSize.height + controlWH * 2.0))
        updateControlTransfrom()
    }
    
    private func maxSelfWith() -> CGFloat {
        return maxContentWith() + controlWH * 2.0
    }
    
    private func maxContentWith() -> CGFloat {
        guard let superView = superview else { return 0 }
        // 最大为父视图宽度*0.5
        return superView.frame.size.width * 0.5
    }
}


extension NNAddTextView {
    
    @objc func tapAction(sender: UITapGestureRecognizer) {
        updateEditingStatus(isEditing: !isEditing)
    }

        
    // 拖拽
    @objc func panAction(sender: UIPanGestureRecognizer) {
        switch sender.state {
        case .changed:
            let translation = sender.translation(in: superview)
            let tobeCenter = CGPoint(x: center.x + translation.x,
                                     y: center.y + translation.y)
            center = tobeCenter
            sender.setTranslation(.zero, in: superview)
        default:
            break
        }
    }
    
    // 缩放
    @objc func rotateControlAction(sender: UIPanGestureRecognizer) {
        
        guard let superView = superview else { return }

        switch sender.state {
        case .began:
            lastControlPoint = sender.location(in: superView)
        case .changed:
            let currentControlPoint = sender.location(in: superView)
            
            let preDistance = distance(start: superView.center, end: lastControlPoint)
            let newDistance = distance(start: superView.center, end: currentControlPoint)

            let changed = (newDistance - preDistance) / preDistance

            zoomScale = 1.0 + changed
            transform = transform.scaledBy(x: zoomScale, y: zoomScale)

            updateControlTransfrom()
            lastControlPoint = currentControlPoint
        default:
            break
        }
    }
    
    // 移除
    @objc func removeAction(sender: UITapGestureRecognizer) {
        removeFromSuperview()
    }
    
    // 编辑
    @objc func editAction(sender: UITapGestureRecognizer) {
        delegate?.shouldBeginEditing(addtextView: self)
    }
}



extension NNAddTextView {
    // 计算两点之间的距离
    func distance(start: CGPoint, end: CGPoint) -> CGFloat {
        let x: CGFloat = start.x - end.x
        let y: CGFloat = start.y - end.y
        return sqrt(x * x + y * y)
    }
}

extension NNAddTextView: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
    
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if gestureRecognizer.view == self {
            if self.rotateCtrl.frame.contains(touch.location(in: self)) {
                return false
            }
        }
        return true
    }
}
